package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.Voice;
import com.tanhua.dubbo.utils.IdService;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@Service
public class VoiceApiImpl implements VoiceApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;


    /**
     * 保存语音文件
     * @param voice
     */
    @Override
    public void save(Voice voice) {
        voice.setId(ObjectId.get());
        voice.setCreated(new DateTime().toString("yyyy-MM-dd"));
        voice.setVoiceId(idService.getNextId("voice"));
        mongoTemplate.save(voice);
    }

    /**
     * 根据userId 今日时间 查询voice
     *
     * @param userId
     * @return count
     */
    @Override
    public int findUserById(Long userId, String time) {
        Query query = new Query(Criteria.where("userId").is(userId).and("created").is(time));
        long count = mongoTemplate.count(query, Voice.class);
        return (int) count;
    }

    /**
     * 根据用户id,语音状态查询数据
     * @param userId
     * @param status
     * @return List<Voice>
     */
    @Override
    public List<Voice> findVoices(Long userId,Integer status) {
        Query query = new Query(Criteria.where("status").is(status).and("userId").ne(userId));
        List<Voice> voiceList = mongoTemplate.find(query, Voice.class);
        return voiceList;
    }

    /**
     * 更新语音状态
     * @param voice
     */
    @Override
    public void update(Voice voice) {
        ObjectId objectId = voice.getId();
        Query query = new Query(Criteria.where("_id").is(objectId));
        Update update = new Update();
        update.set("status", voice.getStatus());
        mongoTemplate.updateFirst(query, update, Voice.class);
    }


}
